﻿using LogForParameter.IServices;
using LogForParameter.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Library.GlobalVars;
using LogForParameter.Api.SwaggerHelp;
using AutoMapper;
using Library.Helper;
using Library.Common.Helper;
using LogForParameter.IServices.ActivityService;
using Quartz;
using QuartzTest;
using LogForParameter.Api.Controllers.JobInstance;
using System.Collections.Generic;
using Library.Common;
using NPOI.HPSF;

namespace LogForParameter.Api.Controllers
{
    [CustomRoute(CustomApiVersion.MyApiVersion.GTestDemo)]
    [ApiController]
    public class ActivityController : ControllerBase
    {
        /// <summary>
        /// 服务器接口，因为是模板生成，所以首字母是大写的，自己可以重构下
        /// </summary>
        private readonly IActivityServices _activityServices;
        private readonly IQuartzServer _quartzServer;
        public ActivityController(IActivityServices ActivityServices, IQuartzServer quartzServer)
        {
            _activityServices = ActivityServices;
            _quartzServer = quartzServer;
        }
        [HttpGet]
        public string NoticeTest(string phoneNumber, string content)
        {
            return _activityServices.NoticeTest(phoneNumber, content);
        }
        [HttpGet]
        public async Task<MessageModel<PageModel<Activity>>> Get(int page = 1, string key = "", int intPageSize = 50)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }

            Expression<Func<Activity, bool>> whereExpression = a => true;

            return new MessageModel<PageModel<Activity>>()
            {
                msg = "获取成功",
                success = true,
                response = await _activityServices.QueryPage(whereExpression, page, intPageSize)
            };

        }

        /// <summary>
        /// 测试启动计划
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<string>> StartASM()
        {
            await _quartzServer.Start();
            return new MessageModel<string>()
            {
                msg = "计划启动",
                success = true
            };
        }
        /// <summary>
        /// 测试添加执行任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<string>> AddASM()
        {
            var jobDetail = JobBuilder.Create(typeof(ASMJOB)).SetJobData(new JobDataMap { new System.Collections.Generic.KeyValuePair<string, object>("ActivityId", 1) }).Build();//可以不带参数
            int repeatCount = Appsettings.App(new string[] { "Quartz", "RepeatCount" }).ObjToInt();
            int Interval = Appsettings.App(new string[] { "Quartz", "Interval" }).ObjToInt();
            var triggerBulder = TriggerBuilder.Create().StartNow().WithIdentity("activityNotice").WithSimpleSchedule(m =>
            {
                m.WithIntervalInSeconds(Interval);
                m.RepeatForever();
            });
            var trigger = triggerBulder.Build();
            await _quartzServer.AddJob(jobDetail, trigger);
            return new MessageModel<string>()
            {
                msg = "任务开始",
                success = true
            };
        }
        /// <summary>
        /// 测试结束整个任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<string>> StopASM()
        {
            await _quartzServer.Stop();
            return new MessageModel<string>()
            {
                msg = "计划停止",
                success = true,
            };
        }
        /// <summary>
        /// 获取工作状态
        /// </summary>
        /// <param name="group">组</param>
        /// <param name="name">名</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<object>> GetJobStatus(string group, string name)
        {
            JobKey jobKey = null;
            if (!string.IsNullOrEmpty(group) && !string.IsNullOrEmpty(name))
                jobKey = new JobKey(name, group);
            else
            {
                jobKey = new JobKey("activity_startnotice", "activity");
            }
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            keyValues.Add("scheduler", await _quartzServer.GetSchedulerStatus());
            keyValues.Add("trigger", await _quartzServer.GetTriggersStatus(jobKey));
            keyValues.Add("job", await _quartzServer.GetJobStatus(jobKey));
            return new MessageModel<object>()
            {
                msg = "获取工作状态",
                success = true,
                response = keyValues
            };
        }
        /// <summary>
        /// 暂停任务
        /// </summary>
        /// <param name="group"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<object>> PauseJob(string group, string name)
        {
            JobKey jobKey = null;
            if (!string.IsNullOrEmpty(group) && !string.IsNullOrEmpty(name))
                jobKey = new JobKey(name, group);
            else
            {
                jobKey = new JobKey("activity_startnotice", "activity");
            }
            await _quartzServer.PauseJob(jobKey);
            return new MessageModel<object>()
            {
                msg = "任务暂停",
                success = true,
            };
        }
        /// <summary>
        /// 恢复任务
        /// </summary>
        /// <param name="group"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<object>> ResumeJob(string group, string name)
        {
            JobKey jobKey = null;
            if (!string.IsNullOrEmpty(group) && !string.IsNullOrEmpty(name))
                jobKey = new JobKey(name, group);
            else
            {
                jobKey = new JobKey("activity_startnotice", "activity");
            }
            await _quartzServer.ResumeJob(jobKey);
            return new MessageModel<object>()
            {
                msg = "恢复任务",
                success = true,
            };
        }
        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="group"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<object>> DeleteJob(string group, string name)
        {
            JobKey jobKey = null;
            if (!string.IsNullOrEmpty(group) && !string.IsNullOrEmpty(name))
                jobKey = new JobKey(name, group);
            else
            {
                jobKey = new JobKey("activity_startnotice", "activity");
            }
            await _quartzServer.DeleteJob(jobKey);
            return new MessageModel<object>()
            {
                msg = "删除任务",
                success = true,
            };
        }
    }
}